import json
from functools import wraps
from typing import Any

from auditlog.context import set_actor
from django.contrib.auth.models import User

FunResult = Any


def login_for_logs_by_mpp(func):  # noqa: ANN201
    """Функция которая принимает другую функцию."""

    @wraps(func)
    def wrapper(*args, **kwargs) -> FunResult:  # noqa: ANN002, ANN003
        """Оберточная функция для логирования от лица пользователя."""
        request = args[0]
        params = json.loads(request.body)
        if request.method == "GET":
            username = request.GET.get("username")
        if request.method == "POST":
            username = params.get("username", False)
        if request.method == "DELETE":
            username = params.get("username", False)
        print(username)
        if not username:
            return func(*args, **kwargs)
        user = User.objects.get(username=username)
        with set_actor(user):
            return func(*args, **kwargs)
    return wrapper
